package lambda;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Test1 {

    @Test
    public void test1(){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("多线程");
            }
        };
        Runnable runable2 = ()-> {
            System.out.println("lambda");
        };
        Runnable runnable3 = () -> System.out.println("simplist lambda");
    }

    @Test
    public void test2(){
        List<Integer> myList = new ArrayList<>();
        for(int i = 0; i <100; i ++) myList.add(i);
        //有序
        Stream<Integer> sequenceStream = myList.stream();
        //并行
        Stream<Integer> parallelStream = myList.parallelStream();

        Stream<Integer> highNums = parallelStream.filter(p -> p > 90);
        highNums.forEach(p -> System.out.println("最大数 并行 = " + p));

        Stream<Integer> highNumsSeq = sequenceStream.filter(p -> p > 90);
        highNumsSeq.forEach(p -> System.out.println("最大数 有序" + p));
    }

    //使用表达式计算质数(除了0,1本身以外的不能被其他数整除的数）
    private static boolean isPrime(int number){
        return number > 1 && IntStream.range(2, number).noneMatch(index -> number % index == 0);
    }

    //使用表达式计算质数(除了0,1本身以外的不能被其他数整除的数）可读性更好（比上一个）
    private static boolean isPrime_2(int number){
        IntPredicate isDivsible = index -> number % index == 0;
        return number > 1 && IntStream.range(2, number).noneMatch(isDivsible);
    }

    //根据条件计算集合值的例子
    public static int sumWithCondition(List<Integer> numbers, Predicate<Integer> predicate){
        return numbers.parallelStream().filter(predicate)
                .mapToInt(i -> i).sum();
    }

    public static int findSquareOfMaxOdd(List<Integer> numbers) {
        return numbers.stream()
                .filter(Test1::isOdd)
                .filter(Test1::isGreaterThan3)
                .filter(Test1::isLessThan11)
                .max(Comparator.naturalOrder())
                .map(i -> i * i)
                .get();
    }

    public static boolean isOdd(int i) {
        return i % 2 != 0;
    }

    public static boolean isGreaterThan3(int i){
        return i > 3;
    }

    public static boolean isLessThan11(int i){
        return i < 11;
    }


}
